<template>
    <div class="app">
        <div id="printTable">
            <div class="input-group">
                <el-autocomplete
                    v-model="matchname"
                    :fetch-suggestions="queryMatchSuggestions"
                    placeholder="请输入比赛名称"
                    @select="handleMatchSelect"
                    class="no-print"
                ></el-autocomplete>
                <el-autocomplete
                    v-model="teamname"
                    :fetch-suggestions="queryTeamSuggestions"
                    placeholder="请输入团队名称"
                    @select="handleTeamSelect"
                    class="no-print"
                ></el-autocomplete>
                <el-button type="primary" @click="deleteproject" class="no-print">清空</el-button>
            </div>
            <div class="titleipt">
                <h1>团队信息汇总表</h1>
            </div>
            <div class="titleipt" id="titlemessage">
                <h2>{{ team[0] ? team[0].teamName : '' }}基本信息</h2>
            </div>
            <div class="titleipt" id="titlemessage">
                <h3>队伍信息</h3>
            </div>
            <el-table :data="team" style="width: 100%">
                <el-table-column prop="id" label="队伍号" width="180"/>
                <el-table-column prop="teamName" label="队伍名称" width="180"/>
                <el-table-column prop="teamAbbreviation" label="队伍简称"/>
                <el-table-column prop="teamLeader" label="负责人"/>
                <el-table-column prop="phone" label="负责人电话"/>
                <el-table-column prop="email" label="负责人邮箱"/>
                <el-table-column prop="address" label="地址"/>
                <el-table-column label="责任书">
                    <template #default="{ row }">
                        <img :src="serverUrl+row.image" alt="" style="width: 80px;height: 80px;">
                    </template>
                </el-table-column>
            </el-table>
            <div class="titleipt" id="titlemessage">
                <h3>成员信息</h3>
            </div>
            <el-table :data="staffs" style="width: 100%">
                <el-table-column prop="id" label="成员号" width="180" />
                <el-table-column prop="userName" label="姓名" width="180" />
                <el-table-column prop="sex" label="性别" />
                <el-table-column prop="role" label="身份" />
                <el-table-column label="组别" width="150">
                    <template #default="{ row }">
                        <span>{{ groupname(row.matchesGroupId) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="idcard" label="身份证号" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column prop="phone" label="手机" />
                <el-table-column label="照片">
                    <template #default="{ row }">
                        <img :src="serverUrl + row.image" alt="" style="width: 80px;height: 80px;">
                    </template>
                </el-table-column>
            </el-table>
            <div class="titleipt" id="titlemessage">
                <h3>队伍项目申报信息</h3>
            </div>
            <el-table :data="project" style="width: 100%">
                <el-table-column label="项目名" width="150">
                    <template #default="{ row }">
                        <span>{{ projectname(row.projectid) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="参报人员" width="150">
                    <template #default="{ row }">
                        <div v-for="staff, index in row.userIds" :key="index">
                            <p>{{ username(staff) }}</p>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="申报难度">
                    <template #default="{ row }">
                        <div v-for="routineid, index in row.routine" :key="index">
                            <p style="float: left;">申报 {{ index + 1 }}:[{{ routineid.content }}({{ routineid.code }}){{
                                routineid.score }}]&nbsp;&nbsp;&nbsp;&nbsp;</p>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="btn">
            <el-button type="primary" v-print="'#printTable'" @click="handlePrint">打印</el-button>
            <el-button type="warning" @click="goBack">关闭</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted,watch } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const matchname = ref('');
const matchId = ref('');
const teamId = ref('');
const teamname = ref('');
const serverUrl = ref('http://back1.idcfengye.com:15173');
const token = localStorage.getItem('adminToken');

const group = ref([]);
const projectid = ref([]);
const match = ref([]);
const matchprojectid = ref();
const project = ref([]);
const staffs = ref([]);
const team = ref([]);


// 获取所有比赛的组别信息
async function fetchgroupData() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/group/admin`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    group.value = response.data.data; // 确保后端返回的数据结构与此匹配
  } catch (error) {
    console.log(error);
  }
}

// 获取matchid对应项目
async function projectidmatch(){
    try{
        const response = await axios.get(`http://back1.idcfengye.com:15173/competition/project/${matchId.value}`,{
            headers:{
                'Authorization': `Bearer ${token}`
            }
        })
        projectid.value = response.data.project || [];
        
    }catch(error){
        console.error('未找到对应项目:', error);
    }
}

//获取所有比赛
async function matchproject() {
  try {
    const response = await axios.get(`${serverUrl.value}/competition/match`, {
      headers: { 'Authorization': `Bearer ${token}` },
    });
    match.value = response.data.matches || [];
  } catch (error) {
    console.error('未找到对应项目:', error);
  }
}

matchproject();

// 获取matchid对应队伍
async function projectmatchid() {
  try {
    const response = await axios.get(`${serverUrl.value}/competition/teamstaff/staff/team/${matchId.value}`, {
      headers: { 'Authorization': `Bearer ${token}` },
    }); 
    matchprojectid.value = response.data.staffs|| [];
  } catch (error) {
    console.error('未找到对应项目:', error);
  }
}

// 获取队伍信息
async function fetchTeamData() {
    if(!teamId.value) return;
  try {
    const response = await axios.get(`${serverUrl.value}/competition/teamgroup/${teamId.value}`, {
      headers: { 'Authorization': `Bearer ${token}` },
    });
    team.value = [response.data.teamGroup];    
  } catch (error) {
    console.log(error);
  }
}

// 获取队伍成员信息
async function fetchStaffData() {
    if(!teamId.value) return;
    try {
        const response = await axios.get(`${serverUrl.value}/competition/teamstaff/staff/${teamId.value}`, {
          headers: { 'Authorization': `Bearer ${token}` },
        });
        staffs.value = response.data.staffs; 
    } catch (error) {
        console.log(error);
    }
}

// 获取队伍报名项目的数据难度申报和参报人员id
async function fetchProjectData() {
    try {
        const response = await axios.get(`${serverUrl.value}/competition/teamstaff/staff/project/${teamId.value}`, {
          headers: { 'Authorization': `Bearer ${token}` },
        });        
        project.value = response.data.staffs; 
    } catch (error) {
        console.log(error);
    }
}

//根据id获取组别名
function groupname(id) {
    const groupname = group.value.find(group => group.id === id);
    return groupname ? groupname.groupname : '';
}

// 根据id获取用户名
function username(id) {
    const staff = staffs.value.find(staff => staff.id === parseInt(id));
    return staff ? staff.id+staff.userName : '';
}

// 根据id获取项目名
function projectname(id) {    
    const projectname = projectid.value.find(project => project.id === id);
    return projectname ? projectname.projectName : '';
}

function goBack() {
  router.back();
}

// 搜索比赛建议
function queryMatchSuggestions(queryString, cb) {
  const results = queryString
    ? match.value.filter(item => item.title.toLowerCase().includes(queryString.toLowerCase()))
    : match.value;
  cb(results.map(item => ({ value: item.title, id: item.id })));
}

// 搜索团队建议
function queryTeamSuggestions(queryString, cb) {
  const results = queryString
    ? matchprojectid.value.filter(item => item.teamName.toLowerCase().includes(queryString.toLowerCase()))
    : matchprojectid.value;
  cb(results.map(item => ({ value: item.teamName, id: item.id })));
}

// 监听比赛ID变化
watch(matchId, (newMatchId) => {
  teamId.value = '';
  projectmatchid();
});

// 监听团队ID变化
watch(teamId, (newTeamId) => {
  fetchData();
});

// 选择比赛后的处理
function handleMatchSelect(item) {
  matchname.value = item.value;
  matchId.value = item.id;
}

// 选择团队后的处理
function handleTeamSelect(item) {    
  teamname.value = item.value;
  teamId.value = item.id;
}

function deleteproject(){
    matchname.value = '';
    teamname.value = '';
}

//调用储存数据
async function fetchData() {
    await fetchgroupData();
    await matchproject();
    await projectidmatch();
    fetchTeamData();
    fetchStaffData();
    fetchProjectData();
}

onMounted(() => {
  fetchData();
});

function handlePrint() {
    const printElements = document.querySelectorAll('.input-group, .btn');
    printElements.forEach(el => (el.style.display = 'none'));
    window.print();
    printElements.forEach(el => (el.style.display = ''));
}
</script>

<style lang="less" scoped>
.app {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
}

.input-group {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
}

.el-table .warning-row {
    background: oldlace !important;
}

.el-table .success-row {
    background: #f0f9eb !important;
}

.btn {
    text-align: center;
}

.titleipt {
    text-align: center;
}

.titleh {
    display: inline-block;
    font-size: 14px !important;
}

#titlemessage {
    border: 1px solid #dcdfe6;
    height: 40px !important;
    line-height: 1px;
}
.inputfirst {
    border-right: beige;
}

/deep/ .el-input-group__prepend {
    color: black;
}

/deep/ .cell {
    color: black;
}
@media print {
    .no-print {
        display: none !important;
    }
}
</style>